﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace AdbRegisterUtils
{
    public static class AdbCommandManager
    {
        private static CmdTerminalService _commandTerminalService;
        private static Action<string, string> _commandOutputCallback;
        private static string _selectedDevice = string.Empty;
        private static int _port = 6666;
        private static bool _isInitialized = false;
        private static readonly object _lockObject = new object();
        private static bool _isExecutingCommand = false;

        // 命令常量定义
        private const string devicesCommand = "devices";
        private const string tcpipCommand = "tcpip";
        private const string connectCommand = "connect";

        /// <summary>
        /// 初始化命令管理器
        /// </summary>
        public static void Initialize(Action<string, string> commandOutputCallback = null)
        {
            try
            {
                lock (_lockObject)
                {
                    if (_isInitialized)
                    {
                        SendCommandOutput("命令管理器已初始化");
                        return;
                    }

                    // 使用 ProcessStartInfoManager 创建配置
                    var startInfo = ProcessStartInfoManager.GetDefaultCmdStartInfo();

                    // 初始化命令终端服务
                    _commandTerminalService = new CmdTerminalService(OnCommandOutput, startInfo);
                    _commandOutputCallback = commandOutputCallback;
                    _isInitialized = true;

                    SendCommandOutput("命令管理器已初始化");

                    // 初始化完成后自动发送 root 命令
                    ExecuteAdbCommand("root", false);
                    SendCommandOutput("已自动发送 root 命令");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"初始化命令管理器失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 命令输出回调处理
        /// </summary>
        private static void OnCommandOutput(string commandType, string output)
        {
            if (string.IsNullOrEmpty(output)) return;

            // 过滤掉终端启动消息
            if (output.Contains("CMD 终端已启动") || output.Contains("CMD terminal started"))
                return;

            // 过滤掉设备检测相关的输出
            if (output.Contains("找到") && output.Contains("个ADB设备"))
                return;

            // 过滤掉命令提示符和路径信息
            if (output.Trim().StartsWith("E:\\") && output.Contains(">adb"))
                return;

            // 发送命令输出
            SendCommandOutput(output);
        }

        #region 基本命令方法

        /// <summary>
        /// 清空命令终端缓冲区
        /// </summary>
        public static void ClearCommandBuffer()
        {
            try
            {
                lock (_lockObject)
                {
                    if (_commandTerminalService != null)
                    {
                        _commandTerminalService.ClearOutputBuffer();
                        SendCommandOutput("命令缓冲区已清空");
                    }
                }
            }
            catch (Exception ex)
            {
                SendCommandOutput($"[ERROR] 清空命令缓冲区失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 执行ADB命令（带缓冲区清空选项）
        /// </summary>
        public static void ExecuteAdbCommand(string command, bool includeDevice = false, bool clearBufferBeforeExecute = true)
        {
            lock (_lockObject)
            {
                if (_isExecutingCommand)
                {
                    SendCommandOutput("[INFO] 正在执行其他命令，请稍候...");
                    return;
                }

                _isExecutingCommand = true;

                try
                {
                    if (!_isInitialized)
                    {
                        SendCommandOutput("命令管理器未初始化，正在自动初始化...");
                        Initialize();
                    }

                    if (_commandTerminalService == null)
                    {
                        SendCommandOutput("命令终端未初始化");
                        return;
                    }

                    // 执行前清空缓冲区
                    if (clearBufferBeforeExecute)
                    {
                        ClearCommandBuffer();
                    }

                    string fullCommand = includeDevice && !string.IsNullOrEmpty(_selectedDevice)
                        ? $"adb -s {_selectedDevice} {command}"
                        : $"adb {command}";

                    // 发送命令前的提示
                    SendCommandOutput($"[执行命令] {fullCommand}");

                    _commandTerminalService.SendCommand(fullCommand);
                }
                catch (Exception ex)
                {
                    SendCommandOutput($"[ERROR] 执行命令失败: {ex.Message}");
                }
                finally
                {
                    _isExecutingCommand = false;
                }
            }
        }

        /// <summary>
        /// 发送devices命令
        /// </summary>
        public static void SendDevicesCommand(bool clearBuffer = true)
        {
            ExecuteAdbCommand(devicesCommand, false, clearBuffer);
        }

        /// <summary>
        /// 发送tcpip命令
        /// </summary>
        public static void SendTcpipCommand(string deviceId = null, bool clearBuffer = true)
        {
            string targetDevice = deviceId ?? _selectedDevice;
            if (string.IsNullOrEmpty(targetDevice))
            {
                SendCommandOutput("[ERROR] 请先选择设备或指定设备ID");
                return;
            }

            ExecuteAdbCommand($"{tcpipCommand} {_port}", true, clearBuffer);
        }

        /// <summary>
        /// 发送connect命令
        /// </summary>
        public static void SendConnectCommand(string ipAddress, bool clearBuffer = true)
        {
            if (string.IsNullOrEmpty(ipAddress))
            {
                SendCommandOutput("[ERROR] 请输入设备的IP地址");
                return;
            }

            ExecuteAdbCommand($"{connectCommand} {ipAddress}:{_port}", false, clearBuffer);
        }

        #endregion

        #region 寄存器命令方法

        /// <summary>
        /// 执行寄存器命令
        /// </summary>
        public static void ExecuteRegisterCommand(int operationType, string address, string value = null, string id = "0", bool clearBuffer = true)
        {
            // 移除了设备选中检查，允许在没有选中设备的情况下执行命令
            try
            {
                // 验证操作类型
                if (operationType < 0 || operationType > 3)
                {
                    SendCommandOutput($"[ERROR] 无效的操作类型: {operationType}，应为 0-3");
                    return;
                }

                // 设置命令值
                string commandValue = "0";
                if (operationType == 1 || operationType == 3)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        SendCommandOutput("[ERROR] 写入操作需要提供值参数");
                        return;
                    }
                    commandValue = value;
                }

                // 清理地址和值
                string cleanAddress = address.Replace(" ", "");
                string cleanValue = commandValue.Replace(" ", "");

                // 构建寄存器命令
                string registerCommand = $"\"{operationType},{cleanAddress},{cleanValue},{id}\"";
                string fullCommand = $"shell setprop vendor.extcamera.xxw.ispregctrl {registerCommand}";

                ExecuteAdbCommand(fullCommand, true, clearBuffer);
            }
            catch (Exception ex)
            {
                SendCommandOutput($"[ERROR] 执行寄存器命令失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 读取寄存器值
        /// </summary>
        public static void ReadRegister(string address, string id = "0", bool clearBuffer = true)
        {
            ExecuteRegisterCommand(0, address, null, id, clearBuffer);
        }

        /// <summary>
        /// 写入寄存器值
        /// </summary>
        public static void WriteRegister(string address, string value, string id = "0", bool clearBuffer = true)
        {
            ExecuteRegisterCommand(1, address, value, id, clearBuffer);
        }

        /// <summary>
        /// 读取Sensor寄存器值
        /// </summary>
        public static void ReadSensorRegister(string address, string id = "0", bool clearBuffer = true)
        {
            ExecuteRegisterCommand(2, address, null, id, clearBuffer);
        }

        /// <summary>
        /// 写入Sensor寄存器值
        /// </summary>
        public static void WriteSensorRegister(string address, string value, string id = "0", bool clearBuffer = true)
        {
            ExecuteRegisterCommand(3, address, value, id, clearBuffer);
        }

        /// <summary>
        /// 开启主开关
        /// </summary>
        public static void EnableMainSwitch(bool clearBuffer = true)
        {
            ExecuteAdbCommand("shell setprop vendor.extcamera.xxw.ispdebug 1", false, clearBuffer);
        }

        /// <summary>
        /// 关闭主开关
        /// </summary>
        public static void DisableMainSwitch(bool clearBuffer = true)
        {
            ExecuteAdbCommand("shell setprop vendor.extcamera.xxw.ispdebug 0", false, clearBuffer);
        }

        #endregion

        #region 设备管理方法

        /// <summary>
        /// 通过TCP/IP连接设备
        /// </summary>
        public static void ConnectDeviceViaTcpip(string deviceId, string ipAddress, bool clearBuffer = true)
        {
            if (string.IsNullOrEmpty(deviceId))
            {
                SendCommandOutput("[ERROR] 请先选择要连接的ADB设备");
                return;
            }

            if (string.IsNullOrEmpty(ipAddress))
            {
                SendCommandOutput("[ERROR] 请输入设备的IP地址");
                return;
            }

            try
            {
                // 清空缓冲区
                if (clearBuffer)
                {
                    ClearCommandBuffer();
                }

                // 设置设备为TCP/IP模式 - 使用专门的命令方法
                SendTcpipCommand(deviceId, false); // 不清空缓冲区，保持连续性

                // 短暂延迟
                Thread.Sleep(500);

                // 连接到设备 - 使用专门的命令方法
                SendConnectCommand(ipAddress, false); // 不清空缓冲区，保持连续性

                SendCommandOutput($"正在连接设备: {ipAddress}:{_port}");
            }
            catch (Exception ex)
            {
                SendCommandOutput($"[ERROR] TCP/IP连接失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 断开TCP/IP连接
        /// </summary>
        public static void DisconnectTcpip(string ipAddress, bool clearBuffer = true)
        {
            try
            {
                if (string.IsNullOrEmpty(ipAddress))
                {
                    SendCommandOutput("[ERROR] 请提供要断开连接的IP地址");
                    return;
                }

                // 使用专门的命令方法
                ExecuteAdbCommand($"disconnect {ipAddress}:{_port}", false, clearBuffer);
                SendCommandOutput($"正在断开连接: {ipAddress}:{_port}");
            }
            catch (Exception ex)
            {
                SendCommandOutput($"[ERROR] 断开连接失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 重置命令终端
        /// </summary>
        public static void ResetCommandTerminal()
        {
            try
            {
                lock (_lockObject)
                {
                    if (_commandTerminalService != null)
                    {
                        _commandTerminalService.ResetTerminal();
                        SendCommandOutput("命令终端已重置");
                    }
                }
            }
            catch (Exception ex)
            {
                SendCommandOutput($"[ERROR] 重置命令终端失败: {ex.Message}");
            }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 设置当前选中的设备
        /// </summary>
        public static void SetSelectedDevice(string deviceId)
        {
            _selectedDevice = deviceId;
        }

        /// <summary>
        /// 获取当前选中的设备
        /// </summary>
        public static string GetSelectedDevice()
        {
            return _selectedDevice;
        }

        /// <summary>
        /// 设置端口
        /// </summary>
        public static void SetPort(int port)
        {
            _port = port;
        }

        /// <summary>
        /// 获取端口
        /// </summary>
        public static int GetPort()
        {
            return _port;
        }

        /// <summary>
        /// 直接发送原始命令
        /// </summary>
        public static void SendRawCommand(string command, bool clearBuffer = true)
        {
            if (!_isInitialized)
            {
                SendCommandOutput("命令管理器未初始化，正在自动初始化...");
                Initialize();
            }

            if (clearBuffer)
            {
                ClearCommandBuffer();
            }

            _commandTerminalService?.SendCommand(command);
        }

        /// <summary>
        /// 设置命令输出回调
        /// </summary>
        public static void SetCommandOutputCallback(Action<string, string> callback)
        {
            _commandOutputCallback = callback;
        }

        /// <summary>
        /// 清理资源
        /// </summary>
        public static void Cleanup()
        {
            try
            {
                _commandTerminalService?.Dispose();
                _commandTerminalService = null;
                _commandOutputCallback = null;
                _selectedDevice = string.Empty;
                _isInitialized = false;
                SendCommandOutput("命令管理器已清理");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Cleanup error: {ex.Message}");
            }
        }

        #endregion

        #region 输出处理

        /// <summary>
        /// 发送命令输出
        /// </summary>
        private static void SendCommandOutput(string text)
        {
            try
            {
                _commandOutputCallback?.Invoke("command", text + "\r\n");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"SendCommandOutput error: {ex.Message}");
            }
        }

        #endregion

        #region 公共属性

        public static CmdTerminalService CommandTerminalService => _commandTerminalService;
        public static bool IsRunning => _commandTerminalService?.IsRunning ?? false;
        public static bool IsInitialized => _isInitialized;

        /// <summary>
        /// 获取缓冲区行数
        /// </summary>
        public static int GetBufferLineCount()
        {
            return _commandTerminalService?.GetBufferLineCount() ?? 0;
        }

        /// <summary>
        /// 获取缓冲区内容（用于调试）
        /// </summary>
        public static string[] GetBufferContents()
        {
            return _commandTerminalService?.GetBufferContents() ?? new string[0];
        }

        #endregion
    }
}